<?php

require('parametros/bd.php');

$usernamenotempty=TRUE;
$usernamevalidate=TRUE;
$usernamenotduplicate=TRUE;
$passwordnotempty=TRUE;
$passwordmatch=TRUE;
$passwordvalidate=TRUE;
$captchavalidation= TRUE;

$direnotempty=TRUE;
$emailnotempty=TRUE;

//Check if user submitted the desired password and username
if ((isset($_POST["desired_password"])) && (isset($_POST["desired_username"])) && (isset($_POST["desired_password1"])))  
{	
	function sanitize($data){
	$data=trim($data);
	$data=htmlspecialchars($data);
	$data=pg_escape_string($data);
	return $data;
}

$desired_username=sanitize($_POST["desired_username"]);
$desired_password=sanitize($_POST["desired_password"]);
$desired_password1=sanitize($_POST["desired_password1"]);

$desired_dire=sanitize($_POST["desired_dire"]);
$desired_email=sanitize($_POST["desired_email"]);

//validate email
if (empty($desired_email))
{
	$emailnotempty=FALSE;
}
else
{
	$emailnotempty=TRUE;
}

//validate direccion
if (empty($desired_dire))
{
	$direnotempty=FALSE;
}
else
{
	$direnotempty=TRUE;
}
//validate username
if (empty($desired_username))
{
	$usernamenotempty=FALSE;
}
else
{
	$usernamenotempty=TRUE;
}

if ((!(ctype_alnum($desired_username))) || ((strlen($desired_username)) >11)) 
{
	$usernamevalidate=FALSE;
}
else
{
	$usernamevalidate=TRUE;
}

if (!($fetch = pg_fetch_array( pg_query("SELECT username FROM authentication WHERE username='$desired_username'")))) 
{
	//no records for this user in the MySQL database
	$usernamenotduplicate=TRUE;
}
else 
{
	$usernamenotduplicate=FALSE;
}

//validate password

if (empty($desired_password))
{
	$passwordnotempty=FALSE;
}
else
{
	$passwordnotempty=TRUE;
}

if ((!(ctype_alnum($desired_password))) || ((strlen($desired_password)) < 8))
{
	$passwordvalidate=FALSE;
}
else
{
	$passwordvalidate=TRUE;
}

if ($desired_password==$desired_password1)
{
	$passwordmatch=TRUE;
}
else 
{
	$passwordmatch=FALSE;
}

//Validate recaptcha
require_once('recaptchalib.php');
$resp = recaptcha_check_answer ($privatekey,
                                $_SERVER["REMOTE_ADDR"],
                                $_POST["recaptcha_challenge_field"],
                                $_POST["recaptcha_response_field"]);

if (!$resp->is_valid)
{
	//captcha validation fails
	$captchavalidation=FALSE;
}
else
{
	$captchavalidation=TRUE;	
}

if (($usernamenotempty==TRUE)
&& ($usernamevalidate==TRUE)
&& ($usernamenotduplicate==TRUE)
&& ($passwordnotempty==TRUE)

&& ($direnotempty==TRUE)
&& ($emailnotempty==TRUE)

&& ($passwordmatch==TRUE)
&& ($passwordvalidate==TRUE)
&& ($captchavalidation==TRUE)) {
//The username, password and recaptcha validation succeeds.

//Hash the password
//This is very important for security reasons because once the password has been compromised,
//The attacker cannot still get the plain text password equivalent without brute force.

function HashPassword($input)
{
//Credits: http://crackstation.net/hashing-security.html
//This is secure hashing the consist of strong hash algorithm sha 256 and using highly random salt
$salt = bin2hex(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM)); 
$hash = hash("sha256", $salt . $input); 
$final = $salt . $hash; 
return $final;
}

//$hashedpassword= HashPassword($desired_password);
$hashedpassword= $desired_password;
//Insert username and the hashed password to MySQL database
$desired_password = md5($desired_password);
pg_query("INSERT INTO authentication (username, password) VALUES ('$desired_username', '$desired_password')") or die('error');
//Send notification to webmaster
$message = "New member has just registered: $desired_username";
mail($email, $subject, $message, $from);
//redirect to login page

header(sprintf("Location: %s", 'userindex.php'));	
exit;
}
}
?>
<!DOCTYPE HTML>
<html>
<title>Registrarse</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="js/mootools.js"></script>
		<script type="text/javascript" src="js/imageMenu.js"></script>
		<script type="text/javascript" src="js/ajax.js"></script>
		<link rel="stylesheet" href="css/style.css" type="text/css" media="screen" />
		<link href="css/imageMenu.css" rel="stylesheet" type="text/css" />
</head>
<body >
<?php
	include 'encabezado.php';
?>

<h2>Formulario de Registro</h2>

<br />
<!-- Start of registration form -->
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="POST">
<table>
  <tr>
	<td>Usuario: (<i>alfanum&eacute;rico menor a 12 caracteres</i>)</td>
	<td> <input type="text" class="<?php if (($usernamenotempty==FALSE) || ($usernamevalidate==FALSE) || ($usernamenotduplicate==FALSE))  echo "invalid"; ?>" id="desired_username" name="desired_username"> </td>
  </tr>
  <tr>
  <tr>
	<td>Direccion: (<i>Sus datos seran utilizados para los envios</i>)</td>
	<td> <input type="text" class="<?php if (($direnotempty==FALSE))  echo "invalid"; ?>" id="desired_dire" name="desired_dire"> </td>
  </tr>
  <tr>
	<td>Email: (<i>Direccion valida de mail</i>)</td>
	<td> <input type="text" class="<?php if (($emailnotempty==FALSE))  echo "invalid"; ?>" id="desired_email" name="desired_email"> </td>
  </tr>
  <tr>
    <td>Contrase&ntilde;a: (<i>alfanum&eacute;rico  superior a 8 caracteres</i>)</td>
    <td><input name="desired_password" type="password" class="<?php if (($passwordnotempty==FALSE) || ($passwordmatch==FALSE) || ($passwordvalidate==FALSE)) echo "invalid"; ?>" id="desired_password" ></td>
  </tr>
  <tr>
    <td>Repita su contrase&ntilde;a:</td>
    <td><input name="desired_password1" type="password" class="<?php if (($passwordnotempty==FALSE) || ($passwordmatch==FALSE) || ($passwordvalidate==FALSE)) echo "invalid"; ?>" id="desired_password1" > </td>
  </tr>
  <tr>
    <td>Ingrese el captcha: </td>
    <td> <?php
			require_once('recaptchalib.php');
			echo recaptcha_get_html($publickey);
			?> 
	</td>
  </tr>
  
  <tr>
    <td> </td>
    <td><input type="submit" value="Register"> </td>
  </tr>
</table>
<a href="index.php">Volver al Inicio</a><br />
<!-- Display validation errors -->
<?php if ($captchavalidation==FALSE) echo '<font color="red">Por favor inserte el Captcha correcto</font>'; ?><br />
<?php if ($usernamenotempty==FALSE) echo '<font color="red">Nombre vacio, no permitido</font>'; ?><br />
<?php if ($usernamevalidate==FALSE) echo '<font color="red">El Nombre debe ser alfanumerico y la longitud maxima es de 12</font>'; ?><br />
<?php if ($usernamenotduplicate==FALSE) echo '<font color="red">Por favor ingrese otro Nombre de Usuario</font>'; ?><br />
<?php if ($passwordnotempty==FALSE) echo '<font color="red">Password vacio, no permitido</font>'; ?><br />
<?php if ($passwordmatch==FALSE) echo '<font color="red">El password no coincide</font>'; ?><br />
<?php if ($passwordvalidate==FALSE) echo '<font color="red">El Password debe ser alfanumerico y minimo de 8 caracteres</font>'; ?><br />
<?php if ($captchavalidation==FALSE) echo '<font color="red">Captcha incorrecto</font>'; ?><br />
</form>
<!-- End of registration form -->
<?php
include 'pie.php';
?>